package com.boomkeeper.mail.template;

import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.boomkeeper.core.config.BaseConfig;
import com.boomkeeper.core.model.ChangeOrderData;
import com.boomkeeper.core.utils.MailUtils;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

/**
 * 邮件模板转换，将ftl模板转换成为html string
 * @author Boomkeeper
 *
 */
@Component
public class MailTemplate {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(MailTemplate.class);

	@Autowired
	private Configuration freemarkerConfig;
	
	@Autowired
	private BaseConfig baseConfig;

	public String parseTemplateToHtml(String ftlName) {
		return this.parseToHtmlStr(null, ftlName);
	}
	
	public String parseTemplateToHtml(ChangeOrderData changeOrderData, String ftlName) {
		Map<String, Object> dataMap = MailUtils.transferDataToMap(changeOrderData);
		dataMap.put("lteDateVersion", this.baseConfig.getLteVersion().getDateVersion());
		return this.parseToHtmlStr(dataMap, ftlName);
	}
	
	public String parseToHtmlStr(Map<String, Object> changeOrderData, String ftlName) {
		Writer writer = new StringWriter(2048);
		Template freemarkerTemplate = null;
		try {
			freemarkerTemplate = freemarkerConfig.getTemplate(ftlName);
		} catch (IOException e) {
			LOGGER.error("初始化mail template异常", e);
		}
		
		try {
			freemarkerTemplate.process(changeOrderData, writer);
		} catch (TemplateException | IOException e) {
			LOGGER.error("freemarker template转换异常", e);
		}
		
		String resultStr = writer.toString();

		try {
			writer.flush();
			writer.close();
		} catch (IOException e) {
			LOGGER.error("freemarker template模板转换完成，关闭输出流异常", e);
		}
		
		return resultStr;
	}
}
